let linkedList = {
  head: null,
  length: 0,
}

let MAX_LENGTH = 4

let wechatItem = {
  name: '微信读书',
  id: 'a',
}

let jingDongItem = {
  name: '京东到家',
  id: 'b',
}

let jueJinItem = {
  name: '掘金',
  id: 'c',
}

let meiTuanItem = {
  name: '美团',
  id: 'd',
}

function linkedListUse(list, listItem) {
  let current = list.head
  let isNewItem = false //默认不是新使用的item

  while (current.next.id !== useItem.id) {
    current = current.next
    if (!current.next) {
      // 查到最后一个都还没有找到
      isNewItem = true
      break
    }
  }
  if (isNewItem) {
    // 使用了新的小程序
    useItem.next = list.head
    list.head = useItem
    list.length += 1
  } else {
    // 使用的是已经存在的小程序
    let changedNode = current.next
    let changedNextNode = changedNode.next
    let firstNode = list.head
    if (current === firstNode) {
      // 交换节点为1和2
      changedNode.next = firstNode
      list.head = changedNode
      firstNode.next = changedNextNode
    } else {
      if (changedNextNode) {
        changedNode.next = firstNode.next
        current.next = firstNode
        list.head = changedNode
        firstNode.next = changedNextNode
      }
      // 超出最大长度后面就不再显示
      if (list.length > MAX_LENGTH) {
        let current = list.head
        let count = 0
        while (current.next) {
          count += 1
          if (count === MAX_LENGTH) {
            current.next = null
            list.length = MAX_LENGTH
            break
          }
          current = current.next
        }
      }
    }
  }
}

// 删除一个微信小程序
function linkedNodeDelete(list, deleteItem) {
  let current = list.head
  let hasDeleteItem = true
  // 删除的是链表第一个节点
  if (list.head.id === deleteItem.id) {
    list.head = list.head.next
    list.length -= 1
  } else {
    while (current.next.id !== deleteItem.id) {
      current = current.next
      if (!current.next) {
        // 说明没有在链表中找到该元素
        hasDeleteItem = false
        break
      }
    }
    if (hasDeleteItem) {
      let deleteNode = current.next
      current.next = deleteNode.next
      list.length -= 1
    } else {
      console.error('删除的元素不存在')
    }
  }
}

linkedListAppend(linkedList, wechatItem)
linkedListAppend(linkedList, jingDongItem)
linkedListAppend(linkedList, jueJinItem)
linkedListAppend(linkedList, meiTuanItem)

linkedListUse(linkedList, {
  name: '简书',
  id: 'f',
})
